# -*- coding: utf-8 -*-
"""
Created on Thu Sep 24 09:10:37 2020

@author: Robin
"""

import pandas as pd
from WindPy import *
from lib.IOFile import *
import os
import numpy as np
w.start()

#savepath = 'data'
#readpath = 'data'
savepath = ''
readpath = ''
index_code = '000905.SH'

# In[0]: 数据提取与保存
sectorid = '1000008491000000'    # 中证500
errorid,stockcodes = w.wset("sectorconstituent","date=2020-09-23;sectorid="+sectorid+";field=wind_code,sec_name",usedf = True)
stocklist = ','.join(stockcodes['wind_code'])
# 指标数据
errorid,indi1 = w.wsd(stocklist, "tech_revs5","2019-08-24", "2020-09-22", "Period=W;PriceAdj=B",usedf=True)
errorid,indi2 = w.wsd(stocklist, "tech_turnoverrate10","2019-08-24", "2020-09-22", "Period=W;PriceAdj=B",usedf=True)
errorid,indi3 = w.wsd(stocklist, "tech_tvma6","2019-08-24", "2020-09-22", "Period=W;PriceAdj=B",usedf=True)
errorid,indi4 = w.wsd(stocklist, "tech_tvstd6","2019-08-24", "2020-09-22", "Period=W;PriceAdj=B",usedf=True)
errorid,indi5 = w.wsd(stocklist, "tech_vema5","2019-08-24", "2020-09-22", "Period=W;PriceAdj=B",usedf=True)
# 价格数据
#errorid,StockPriceH = w.wsd(stocklist, "high","2019-08-24", "2020-09-22", "Period=W;PriceAdj=B",usedf=True)
#errorid,StockPriceL = w.wsd(stocklist, "low","2019-08-24", "2020-09-22", "Period=W;PriceAdj=B",usedf=True)
#errorid,StockPriceO = w.wsd(stocklist, "open","2019-08-24", "2020-09-22", "Period=W;PriceAdj=B",usedf=True)
errorid,StockPriceC = w.wsd(stocklist, "close","2019-08-24", "2020-09-22", "Period=W;PriceAdj=B",usedf=True)
#errorid,Volume = w.wsd(stocklist, "volume","2019-08-24", "2020-09-22", "Period=W;PriceAdj=B",usedf=True)
# 数据保存
saveData(indi1,'indi1',savepath)
saveData(indi2,'indi2',savepath)
saveData(indi3,'indi3',savepath)
saveData(indi4,'indi4',savepath)
saveData(indi5,'indi5',savepath)
saveData(StockPriceC,'stockPrice_'+re.sub('[.]','',index_code),savepath)

# In[1]:将数据清洗为alphalens需要的输入格式
indi1 = readjson('indi1',readpath)
indi2 = readjson('indi2',readpath)
indi3 = readjson('indi3',readpath)
indi4 = readjson('indi4',readpath)
indi5 = readjson('indi5',readpath)
StockPriceC = readjson('StockPriceC',readpath)

# 双索引
timeSeries = indi1.index
StockSeries = indi1.columns

StockSeries_m,timeSeries_m = np.meshgrid(StockSeries,timeSeries)
time_stock_Index = pd.MultiIndex.from_arrays(
        [timeSeries_m.reshape(timeSeries_m.size),
         StockSeries_m.reshape(StockSeries_m.size)],
         names = ['tradeDate','StockCode'])

indi_df = pd.DataFrame({'indi1':indi1.values.reshape(indi1.size),
                        'indi2':indi2.values.reshape(indi2.size),
                        'indi3':indi3.values.reshape(indi3.size),
                        'indi4':indi4.values.reshape(indi4.size),
                        'indi5':indi5.values.reshape(indi5.size)},index = time_stock_Index)



